import { Modal, Form, Input, DatePicker, TreeSelect, Select, Row, Col, Button, Icon, Radio } from 'antd';
import '@ant-design/compatible/assets/index.css';
import { useState, useEffect, useCallback } from 'react';
import styles from './NationalRoutes.less';

let id = 0;

export default Form.create()(({ form, choiceSupplier, save, onCancel,selectData }) => {

  const { getFieldDecorator, validateFields, resetFields, getFieldValue, setFieldsValue } = form;

  const searchFormArr = [
    {
      name: '洲际',
      dataIndex: 'continent',
      inputType: 'input',
      placeholder: '请输入洲际',
      require:true,
      message: '洲际只能为<=10个中文字符',
      rule:new RegExp(/^[\u4e00-\u9fa5]{0,10}$/)
    }
  ]

  const [countryArr, setcountryArr] = useState([]);

  const add = () => {
    setcountryArr([...countryArr, ''])
  }

  const formItemLayout = {
    labelCol: {
      xs: { span: 24 },
      sm: { span: 6 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 18 },
    },
  };

  const formItemLayoutWithOutLabel = {
    wrapperCol: {
      xs: { span: 24, offset: 0 },
      sm: { span: 18, offset: 6 },
    },
  };

  const getFields = () => {
    const children = [];
    searchFormArr.forEach((res, idx) => {
      children.push(
        <Col span={24} key={idx}>
          <Form.Item label={res.name} {...formItemLayout}>
            {res.inputType === 'input' && getFieldDecorator(`${res.dataIndex}`, {
              initialValue: res.value,
              rules: [
                {
                  required: res.require,
                  whitespace: true,
                  message: res.message,
                  pattern: res.rule
                },
              ],
            })(<Input placeholder={res.placeholder} />)}
          </Form.Item>
        </Col>
      );
    })
    getFieldDecorator('country', { initialValue: [] });
    return children;
  }

  useEffect(() => {
    if (!choiceSupplier) {
      add();
    } else {
      const CodeArr = (choiceSupplier.country || '').split(',').map(item => item);
      setcountryArr(CodeArr);
      setFieldsValue({
        continent: choiceSupplier.continent,
        currency: choiceSupplier.currency
      })
    }
  }, [choiceSupplier]);

  const remove = k => {
    const newcountryArr = JSON.parse(JSON.stringify(getFieldValue('terminal')));
    newcountryArr.splice(k, 1);
    setcountryArr(newcountryArr);
    setFieldsValue({
      terminal: newcountryArr
    })
  };

  const formItems = useCallback(() => {
    const itemDom = [];
    (countryArr || []).map((k, index) => {
      itemDom.push((
        <Form.Item
          {...(index === 0 ? formItemLayout : formItemLayoutWithOutLabel)}
          label={index === 0 ? '国家' : ''}
          required={true}
          key={`terminal[${index}${k}]`}
        >
          {getFieldDecorator(`terminal[${index}]`, {
            validateTrigger: ['onChange', 'onBlur'],
            initialValue: k,
            rules: [
              {
                required: true,
                whitespace: true,
                message: "请输入国家.",
              },
              {
                validator: async (rule, value, callback) => {
                  if (value && ((value || []).length == 0)) {
                    callback("请输入国家");
                  }
                  callback();
                },
              }
            ],
          })( <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            addonAfter=""
            style={{ width: '90%', marginRight: 8 }}
          >
            {
              selectData&&selectData.map((v,i) => {
                return (
                  <Option key={v.country}>{v.country}</Option>
                )
              })
            }
          </Select>)}
          {Boolean(index > 0) ? (
            <Icon
              className="dynamic-delete-button"
              type="minus-square-o"
              style={{ fontSize: '26px', verticalAlign: '-0.3em' }}
              onClick={() => remove(index)}
            />
          ) : (<Icon
            className="dynamic-delete-button"
            type="plus-square-o"
            style={{ fontSize: '26px', verticalAlign: '-0.3em' }}
            onClick={() => add()}
          />)}
        </Form.Item>
      ))
    });
    return itemDom;
  }, [countryArr]);

  const handleSave = () => {
    validateFields((err, values) => {
      // console.log(values);
      if (!err) {
        save(values);
      }
    });
  }

  return (
    <>
      <Form>
        <Row gutter={24}>{getFields()}</Row>
        <div>
          {formItems()}
        </div>
        <div className={styles.modalButton}>
          <Button type="primary" onClick={handleSave}>
            确定
          </Button>
          <Button type="primary" onClick={onCancel}>
            取消
          </Button>
        </div>
      </Form>
    </>
  )
})
